package com.example.interceptor;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.pojo.CommonJSONResult;
import com.utils.JsonUtils;

public class OneInterceptor implements HandlerInterceptor  {

	/**
	 * 在请求处理之前进行调用（Controller方法调用之前）
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object object) throws Exception {
		
		System.out.println("被one拦截，放行...");
		return true;
		
		/*if (true) {
			returnErrorResponse(response, CommonJSONResult.errorMsg("被one拦截..."));
		}
		
		return false;*/
	}
	
	/**
	 * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
			Object object, ModelAndView mv)
			throws Exception {
		System.out.println("controller处理后，页面渲染前：" + Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8)));
		
	}
	
	/**
	 * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行
	 * （主要是用于进行资源清理工作）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object object, Exception ex)
			throws Exception {
		System.out.println("页面渲染完成，处理结束：" + Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8)));
		
	}
	
	public void returnErrorResponse(HttpServletResponse response, CommonJSONResult result) 
			throws IOException, UnsupportedEncodingException {
		OutputStream out=null;
		try{
		    response.setCharacterEncoding("utf-8");
		    response.setContentType("text/json");
		    out = response.getOutputStream();
		    out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
		    out.flush();
		} finally{
		    if(out!=null){
		        out.close();
		    }
		}
	}
	
	private static final Random r = new Random();
	
	static int random(int n) {
		return Math.abs(r.nextInt()) % n;
	}
	
	public static void main(String[] args) {
		int n = 2 * (Integer.MAX_VALUE / 3);
		int low = 0;
		for (int i = 0; i < 1000000; i++) {
			if (random(n) < n/2) {
				low++;
			}
		}
		System.out.println(low);
		
		// 标准类库更接近500000
		int low1 = 0;
		for (int i = 0; i < 1000000; i++) {
			if (r.nextInt(n) < n/2) {
				low1++;
			}
		}
		System.out.println(low1);
		
	}
}
